import { Attendance } from '../models/Attendance.js';
import { Student } from '../models/Student.js';
import { Class } from '../models/Class.js';
import { CourseModel } from '../models/Course.js';
import { ClassGrade } from '../models/ClassGrade.js';

export class AttendanceController {
    constructor() {
        this.attendanceModel = new Attendance();
        this.studentModel = new Student();
        this.classModel = new Class();
        this.courseModel = new CourseModel();
        this.classGradeModel = new ClassGrade();
    }

    // 获取课程列表（用于选择课程）
    async getCourses(req, res) {
        try {
            const courses = this.courseModel.findAll();
            res.json({
                success: true,
                data: courses
            });
        } catch (error) {
            console.error('获取课程列表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取课程列表失败',
                message: error.message
            });
        }
    }

    // 根据课程ID获取关联的班级列表
    async getClassesByCourse(req, res) {
        try {
            const { courseId } = req.params;
            const course = this.courseModel.findById(parseInt(courseId));

            if (!course) {
                return res.status(404).json({
                    success: false,
                    error: '课程不存在'
                });
            }

            // 通过ClassGrade查找关联的班级
            const classGrades = this.classGradeModel.findByCourseCode(course.code);

            // 获取所有班级
            const allClasses = this.classModel.findAll();

            // 找出关联的班级
            const relatedClasses = allClasses.filter(cls => {
                return classGrades.some(cg => cg.className === cls.className);
            });

            // 如果ClassGrade中没有关联，返回所有班级（兼容处理）
            const classes = relatedClasses.length > 0 ? relatedClasses : allClasses;

            res.json({
                success: true,
                data: classes
            });
        } catch (error) {
            console.error('获取班级列表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取班级列表失败',
                message: error.message
            });
        }
    }

    // 根据班级获取学生列表
    async getStudentsByClass(req, res) {
        try {
            const { classId } = req.params;
            const classItem = this.classModel.findById(parseInt(classId));

            if (!classItem) {
                return res.status(404).json({
                    success: false,
                    error: '班级不存在'
                });
            }

            // 根据班级名称获取学生
            const students = this.studentModel.findByClass(classItem.className);

            res.json({
                success: true,
                data: students
            });
        } catch (error) {
            console.error('获取学生列表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取学生列表失败',
                message: error.message
            });
        }
    }

    // 创建一节课的考勤记录（批量创建，生成考勤记录表）
    async createLessonAttendance(req, res) {
        try {
            const {
                courseId,
                courseName,
                classId,
                className,
                date,
                coursePeriod,
                teacher,
                studentAttendances // 数组，包含每个学生的考勤状态 [{studentId, status, remark}]
            } = req.body;

            if (!courseId || !courseName || !classId || !className || !date || !studentAttendances || !Array.isArray(studentAttendances)) {
                return res.status(400).json({
                    success: false,
                    error: '请提供完整的考勤信息：课程ID、课程名称、班级ID、班级名称、日期、学生考勤记录数组'
                });
            }

            // 验证课程是否存在
            const course = this.courseModel.findById(parseInt(courseId));
            if (!course) {
                return res.status(404).json({
                    success: false,
                    error: '课程不存在'
                });
            }

            // 验证班级是否存在
            const classItem = this.classModel.findById(parseInt(classId));
            if (!classItem) {
                return res.status(404).json({
                    success: false,
                    error: '班级不存在'
                });
            }

            // 获取班级的学生列表用于验证
            const students = this.studentModel.findByClass(classItem.className);
            const studentMap = new Map(students.map(s => [String(s.id), s]));

            // 验证学生记录
            const validStatuses = ['present', 'late', 'absent', 'leave', 'early'];
            const createdAttendances = [];
            const errors = [];

            for (const item of studentAttendances) {
                const { studentId, status, remark } = item;

                if (!studentId || !status) {
                    errors.push(`学生ID ${studentId} 缺少必要信息`);
                    continue;
                }

                if (!validStatuses.includes(status)) {
                    errors.push(`学生ID ${studentId} 的考勤状态无效`);
                    continue;
                }

                const student = studentMap.get(String(studentId));
                if (!student) {
                    errors.push(`学生ID ${studentId} 不属于该班级`);
                    continue;
                }

                // 检查是否已经存在相同的考勤记录（同一课程、班级、日期、时段、学生）
                const existing = this.attendanceModel.findAll().find(a =>
                    a.courseName === courseName &&
                    a.className === className &&
                    a.date === date &&
                    a.coursePeriod === (coursePeriod || 1) &&
                    a.studentId === String(studentId)
                );

                if (existing) {
                    // 如果已存在，更新记录
                    const updated = this.attendanceModel.update(existing.id, {
                        status,
                        remark: remark || '',
                        teacher: teacher || course.teacher || '',
                        updatedAt: new Date().toISOString()
                    });
                    if (updated) {
                        createdAttendances.push(updated);
                    }
                } else {
                    // 创建新记录
                    const attendance = {
                        studentId: String(studentId),
                        studentName: student.name || '',
                        className,
                        date,
                        coursePeriod: coursePeriod || 1,
                        courseName,
                        status,
                        teacher: teacher || course.teacher || '',
                        leaveImage: '',
                        isLateNight: false,
                        remark: remark || ''
                    };

                    const created = this.attendanceModel.create(attendance);
                    createdAttendances.push(created);
                }
            }

            res.status(201).json({
                success: true,
                data: createdAttendances,
                count: createdAttendances.length,
                errors: errors.length > 0 ? errors : undefined
            });
        } catch (error) {
            console.error('创建考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '创建考勤记录失败',
                message: error.message
            });
        }
    }

    // 获取一节课的考勤记录表（根据课程、班级、日期、时段）
    async getLessonAttendance(req, res) {
        try {
            const { courseId, classId, date, coursePeriod } = req.query;

            if (!courseId || !classId || !date) {
                return res.status(400).json({
                    success: false,
                    error: '请提供课程ID、班级ID和日期'
                });
            }

            // 获取课程和班级信息
            const course = this.courseModel.findById(parseInt(courseId));
            const classItem = this.classModel.findById(parseInt(classId));

            if (!course) {
                return res.status(404).json({
                    success: false,
                    error: '课程不存在'
                });
            }

            if (!classItem) {
                return res.status(404).json({
                    success: false,
                    error: '班级不存在'
                });
            }

            // 获取该班级的所有学生
            const students = this.studentModel.findByClass(classItem.className);

            // 获取已存在的考勤记录
            const attendances = this.attendanceModel.findAll().filter(a =>
                a.courseName === course.name &&
                a.className === classItem.className &&
                a.date === date &&
                (coursePeriod ? a.coursePeriod === parseInt(coursePeriod) : true)
            );

            // 构建学生考勤记录（如果已存在则使用已有记录，否则使用默认值）
            const studentAttendanceMap = new Map(
                attendances.map(a => [a.studentId, a])
            );

            const lessonAttendance = students.map(student => {
                const existing = studentAttendanceMap.get(String(student.id));
                return {
                    studentId: student.id,
                    studentName: student.name,
                    studentNo: student.studentId,
                    status: existing ? existing.status : 'present', // 默认为出勤
                    remark: existing ? existing.remark || '' : ''
                };
            });

            res.json({
                success: true,
                data: {
                    courseId: course.id,
                    courseName: course.name,
                    classId: classItem.id,
                    className: classItem.className,
                    date,
                    coursePeriod: coursePeriod ? parseInt(coursePeriod) : 1,
                    teacher: course.teacher || '',
                    students: lessonAttendance
                }
            });
        } catch (error) {
            console.error('获取考勤记录表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤记录表失败',
                message: error.message
            });
        }
    }

    // 获取考勤记录列表
    async getAttendances(req, res) {
        try {
            const {
                page = 1,
                pageSize = 10,
                studentId,
                className,
                date,
                courseName,
                status,
                startDate,
                endDate
            } = req.query;

            let attendances = this.attendanceModel.findAll();

            // 应用过滤条件
            if (studentId) {
                attendances = attendances.filter(a => a.studentId === String(studentId));
            }
            if (className) {
                attendances = attendances.filter(a => a.className === className);
            }
            if (date) {
                attendances = attendances.filter(a => a.date === date);
            }
            if (courseName) {
                attendances = attendances.filter(a => a.courseName === courseName);
            }
            if (status) {
                attendances = attendances.filter(a => a.status === status);
            }
            if (startDate && endDate) {
                attendances = attendances.filter(a => {
                    const attendanceDate = new Date(a.date);
                    const start = new Date(startDate);
                    const end = new Date(endDate);
                    return attendanceDate >= start && attendanceDate <= end;
                });
            }

            // 排序：按日期倒序，然后按创建时间倒序
            attendances.sort((a, b) => {
                const dateCompare = new Date(b.date) - new Date(a.date);
                if (dateCompare !== 0) return dateCompare;
                return new Date(b.createdAt) - new Date(a.createdAt);
            });

            // 分页
            const pageNum = parseInt(page);
            const size = parseInt(pageSize);
            const startIndex = (pageNum - 1) * size;
            const endIndex = startIndex + size;
            const paginatedAttendances = attendances.slice(startIndex, endIndex);

            res.json({
                success: true,
                data: paginatedAttendances,
                pagination: {
                    current: pageNum,
                    pageSize: size,
                    total: attendances.length,
                    totalPages: Math.ceil(attendances.length / size)
                }
            });
        } catch (error) {
            console.error('获取考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤记录失败',
                message: error.message
            });
        }
    }

    // 获取考勤详细记录（根据课程、日期、班级等条件）
    async getAttendanceDetail(req, res) {
        try {
            const {
                courseName,
                date,
                className,
                coursePeriod
            } = req.query;

            let attendances = this.attendanceModel.findAll();

            // 应用过滤条件
            if (courseName) {
                attendances = attendances.filter(a => a.courseName === courseName);
            }
            if (date) {
                attendances = attendances.filter(a => a.date === date);
            }
            if (className) {
                attendances = attendances.filter(a => a.className === className);
            }
            if (coursePeriod) {
                attendances = attendances.filter(a => a.coursePeriod === parseInt(coursePeriod));
            }

            // 按学号排序
            attendances.sort((a, b) => {
                const studentIdA = parseInt(a.studentId) || 0;
                const studentIdB = parseInt(b.studentId) || 0;
                return studentIdA - studentIdB;
            });

            res.json({
                success: true,
                data: attendances
            });
        } catch (error) {
            console.error('获取考勤详情失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤详情失败',
                message: error.message
            });
        }
    }

    // 获取单个考勤记录
    async getAttendanceById(req, res) {
        try {
            const { id } = req.params;
            const attendance = this.attendanceModel.findById(parseInt(id));

            if (!attendance) {
                return res.status(404).json({
                    success: false,
                    error: '考勤记录不存在'
                });
            }

            res.json({
                success: true,
                data: attendance
            });
        } catch (error) {
            console.error('获取考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤记录失败',
                message: error.message
            });
        }
    }

    // 创建考勤记录
    async createAttendance(req, res) {
        try {
            const {
                studentId,
                studentName,
                className,
                date,
                coursePeriod,
                courseName,
                status,
                teacher,
                leaveImage,
                isLateNight
            } = req.body;

            if (!studentId || !className || !date || !courseName || !status) {
                return res.status(400).json({
                    success: false,
                    error: '请提供完整的考勤信息：学号、班级、日期、课程名称、状态'
                });
            }

            // 验证考勤状态
            const validStatuses = ['present', 'late', 'absent', 'leave', 'early'];
            if (!validStatuses.includes(status)) {
                return res.status(400).json({
                    success: false,
                    error: `考勤状态无效，必须是：${validStatuses.join(', ')}`
                });
            }

            const attendance = {
                studentId: String(studentId),
                studentName: studentName || '',
                className,
                date,
                coursePeriod: coursePeriod || 1,
                courseName,
                status,
                teacher: teacher || '',
                leaveImage: leaveImage || '',
                isLateNight: isLateNight || false
            };

            const createdAttendance = this.attendanceModel.create(attendance);

            res.status(201).json({
                success: true,
                data: createdAttendance
            });
        } catch (error) {
            console.error('创建考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '创建考勤记录失败',
                message: error.message
            });
        }
    }

    // 批量创建考勤记录
    async createBatchAttendance(req, res) {
        try {
            // 支持两种格式：{ records: [...] } 或 { attendances: [...] }
            const { records, attendances } = req.body;
            const recordsArray = records || attendances;

            if (!Array.isArray(recordsArray) || recordsArray.length === 0) {
                return res.status(400).json({
                    success: false,
                    error: '请提供考勤记录数组'
                });
            }

            const validStatuses = ['present', 'late', 'absent', 'leave', 'early'];
            const createdAttendances = [];

            for (const item of recordsArray) {
                const {
                    studentId,
                    studentName,
                    className,
                    date,
                    coursePeriod,
                    courseName,
                    status,
                    teacher,
                    leaveImage,
                    isLateNight
                } = item;

                if (!studentId || !className || !date || !courseName || !status) {
                    continue; // 跳过无效记录
                }

                if (!validStatuses.includes(status)) {
                    continue; // 跳过无效状态
                }

                const attendance = {
                    studentId: String(studentId),
                    studentName: studentName || '',
                    className,
                    date,
                    coursePeriod: coursePeriod || 1,
                    courseName,
                    status,
                    teacher: teacher || '',
                    leaveImage: leaveImage || '',
                    isLateNight: isLateNight || false
                };

                const created = this.attendanceModel.create(attendance);
                createdAttendances.push(created);
            }

            res.status(201).json({
                success: true,
                data: createdAttendances,
                count: createdAttendances.length
            });
        } catch (error) {
            console.error('批量创建考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '批量创建考勤记录失败',
                message: error.message
            });
        }
    }

    // 更新考勤记录
    async updateAttendance(req, res) {
        try {
            const { id } = req.params;
            const {
                studentId,
                studentName,
                className,
                date,
                coursePeriod,
                courseName,
                status,
                teacher,
                leaveImage,
                isLateNight
            } = req.body;

            const attendance = this.attendanceModel.findById(parseInt(id));
            if (!attendance) {
                return res.status(404).json({
                    success: false,
                    error: '考勤记录不存在'
                });
            }

            // 验证考勤状态
            if (status) {
                const validStatuses = ['present', 'late', 'absent', 'leave', 'early'];
                if (!validStatuses.includes(status)) {
                    return res.status(400).json({
                        success: false,
                        error: `考勤状态无效，必须是：${validStatuses.join(', ')}`
                    });
                }
            }

            const updateData = {};
            if (studentId !== undefined) updateData.studentId = String(studentId);
            if (studentName !== undefined) updateData.studentName = studentName;
            if (className !== undefined) updateData.className = className;
            if (date !== undefined) updateData.date = date;
            if (coursePeriod !== undefined) updateData.coursePeriod = coursePeriod;
            if (courseName !== undefined) updateData.courseName = courseName;
            if (status !== undefined) updateData.status = status;
            if (teacher !== undefined) updateData.teacher = teacher;
            if (leaveImage !== undefined) updateData.leaveImage = leaveImage;
            if (isLateNight !== undefined) updateData.isLateNight = isLateNight;

            const updatedAttendance = this.attendanceModel.update(parseInt(id), updateData);

            if (updatedAttendance) {
                res.json({
                    success: true,
                    data: updatedAttendance
                });
            } else {
                res.status(500).json({
                    success: false,
                    error: '更新考勤记录失败'
                });
            }
        } catch (error) {
            console.error('更新考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '更新考勤记录失败',
                message: error.message
            });
        }
    }

    // 删除考勤记录
    async deleteAttendance(req, res) {
        try {
            const { id } = req.params;
            console.log('删除考勤记录，ID:', id);

            const success = this.attendanceModel.delete(parseInt(id));

            if (success) {
                console.log('删除考勤记录成功，ID:', id);
                res.json({
                    success: true,
                    message: '删除成功'
                });
            } else {
                console.log('考勤记录不存在，ID:', id);
                res.status(404).json({
                    success: false,
                    error: '考勤记录不存在'
                });
            }
        } catch (error) {
            console.error('删除考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '删除考勤记录失败',
                message: error.message
            });
        }
    }

    // 批量删除考勤记录
    async deleteBatchAttendance(req, res) {
        try {
            const { ids } = req.body;

            if (!Array.isArray(ids) || ids.length === 0) {
                return res.status(400).json({
                    success: false,
                    error: '请提供要删除的记录ID数组'
                });
            }

            console.log('批量删除考勤记录，IDs:', ids);

            const success = this.attendanceModel.deleteMany(ids.map(id => parseInt(id)));

            if (success) {
                console.log('批量删除考勤记录成功');
                res.json({
                    success: true,
                    message: '批量删除成功'
                });
            } else {
                res.status(404).json({
                    success: false,
                    error: '没有找到要删除的记录'
                });
            }
        } catch (error) {
            console.error('批量删除考勤记录失败:', error);
            res.status(500).json({
                success: false,
                error: '批量删除考勤记录失败',
                message: error.message
            });
        }
    }

    // 获取考勤选项数据（学生、班级、教师、课程列表）
    async getAttendanceOptions(req, res) {
        try {
            const students = this.studentModel.findAll();
            const classes = this.classModel.findAll();
            const courses = this.courseModel.findAll();
            const teachers = this.classModel.findAll().map(cls => cls.lecturer).filter(Boolean);

            // 去重
            const uniqueTeachers = [...new Set(teachers)];

            res.json({
                success: true,
                students: students.map(s => ({
                    id: String(s.id),
                    name: s.name,
                    className: s.className,
                    studentId: s.studentId
                })),
                classes: [...new Set(classes.map(cls => cls.className))],
                teachers: uniqueTeachers,
                courses: [...new Set(courses.map(c => c.name))]
            });
        } catch (error) {
            console.error('获取考勤选项失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤选项失败',
                message: error.message
            });
        }
    }

    // 获取课程时间表
    async getCourseSchedule(req, res) {
        try {
            // 默认的课程时间表
            const schedule = [
                { period: 1, time: '08:00-08:45', name: '第1节课' },
                { period: 2, time: '09:00-09:45', name: '第2节课' },
                { period: 3, time: '10:10-10:55', name: '第3节课' },
                { period: 4, time: '11:05-11:50', name: '第4节课' },
                { period: 5, time: '14:00-14:45', name: '第5节课' },
                { period: 6, time: '15:00-15:45', name: '第6节课' },
                { period: 7, time: '16:00-16:45', name: '第7节课' },
                { period: 8, time: '19:00-19:45', name: '第8节课' }
            ];

            res.json(schedule);
        } catch (error) {
            console.error('获取课程时间表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取课程时间表失败',
                message: error.message
            });
        }
    }

    // 获取考勤统计（按学生统计）
    async getAttendanceStats(req, res) {
        try {
            const { className, date, courseName, startDate, endDate } = req.query;

            let attendances = this.attendanceModel.findAll();

            // 应用过滤条件
            if (className) {
                attendances = attendances.filter(a => a.className === className);
            }
            if (date) {
                attendances = attendances.filter(a => a.date === date);
            }
            if (courseName) {
                attendances = attendances.filter(a => a.courseName === courseName);
            }
            if (startDate && endDate) {
                attendances = attendances.filter(a => {
                    const attendanceDate = new Date(a.date);
                    const start = new Date(startDate);
                    const end = new Date(endDate);
                    return attendanceDate >= start && attendanceDate <= end;
                });
            }

            // 按学生统计
            const studentStatsMap = new Map();

            attendances.forEach(attendance => {
                const studentId = attendance.studentId;
                if (!studentStatsMap.has(studentId)) {
                    studentStatsMap.set(studentId, {
                        studentId: studentId,
                        studentName: attendance.studentName || '',
                        className: attendance.className || '',
                        totalCount: 0,
                        presentCount: 0,
                        absentCount: 0,
                        lateCount: 0,
                        leaveCount: 0,
                        earlyCount: 0
                    });
                }

                const stat = studentStatsMap.get(studentId);
                stat.totalCount++;

                switch (attendance.status) {
                    case 'present':
                        stat.presentCount++;
                        break;
                    case 'late':
                        stat.lateCount++;
                        break;
                    case 'absent':
                        stat.absentCount++;
                        break;
                    case 'leave':
                        stat.leaveCount++;
                        break;
                    case 'early':
                        stat.earlyCount++;
                        break;
                }
            });

            // 计算出勤率并转换为数组
            const studentStats = Array.from(studentStatsMap.values()).map(stat => ({
                ...stat,
                attendanceRate: stat.totalCount > 0
                    ? parseFloat(((stat.presentCount + stat.leaveCount) / stat.totalCount * 100).toFixed(2))
                    : 0
            }));

            // 返回数组格式，匹配前端期望的 StudentStat[]
            res.json(studentStats);
        } catch (error) {
            console.error('获取考勤统计失败:', error);
            res.status(500).json({
                success: false,
                error: '获取考勤统计失败',
                message: error.message
            });
        }
    }

    // 获取所有班级及其学生数量（用于考勤管理）
    async getClassesOverview(req, res) {
        try {
            const { courseId, coursePeriod, date } = req.query;

            const classes = this.classModel.findAll();
            const students = this.studentModel.findAll();
            const allAttendances = this.attendanceModel.findAll();

            // 为每个班级统计学生数量和考勤记录数
            const classesWithStudentCount = classes.map(classItem => {
                const classStudents = students.filter(student =>
                    student.className === classItem.className &&
                    student.status === 'active' // 只统计在校学生
                );

                // 统计该班级的考勤记录数（可以根据课程节次和日期筛选）
                let classAttendances = allAttendances.filter(att =>
                    att.className === classItem.className
                );

                // 如果提供了课程节次，只统计该节次的记录
                if (coursePeriod) {
                    classAttendances = classAttendances.filter(att =>
                        att.coursePeriod === parseInt(coursePeriod)
                    );
                }

                // 如果提供了日期，只统计该日期的记录
                if (date) {
                    classAttendances = classAttendances.filter(att =>
                        att.date === date
                    );
                }

                return {
                    id: classItem.id,
                    className: classItem.className,
                    grade: classItem.grade,
                    major: classItem.major,
                    department: classItem.department,
                    lecturer: classItem.lecturer,
                    counselor: classItem.counselor,
                    studentCount: classStudents.length, // 实际学生数量
                    activeStudentCount: classStudents.length, // 在校学生数量
                    attendanceRecordCount: classAttendances.length, // 考勤记录数
                    status: classItem.status
                };
            });

            // 按班级名称排序
            classesWithStudentCount.sort((a, b) => a.className.localeCompare(b.className));

            // 统计总数
            const totalClasses = classesWithStudentCount.length;
            const totalStudents = classesWithStudentCount.reduce((sum, cls) => sum + cls.studentCount, 0);
            const totalRecords = classesWithStudentCount.reduce((sum, cls) => sum + cls.attendanceRecordCount, 0);

            res.json({
                success: true,
                data: {
                    classes: classesWithStudentCount,
                    summary: {
                        totalClasses,
                        totalStudents,
                        totalRecords,
                        averageStudents: totalClasses > 0 ? Math.round(totalStudents / totalClasses) : 0
                    }
                }
            });
        } catch (error) {
            console.error('获取班级概览失败:', error);
            res.status(500).json({
                success: false,
                error: '获取班级概览失败',
                message: error.message
            });
        }
    }
}
